"""
玩家系统模块
处理玩家属性管理、境界提升、背包管理等功能
"""
import random
from typing import Dict, List, Optional, Tuple
from .game_core import GameCore, Player, Realm, Item, ItemType

class PlayerSystem:
    """玩家系统类"""
    
    def __init__(self, game_core: GameCore):
        self.game_core = game_core
        # 境界提升所需经验
        self.realm_exp_requirements = {
            Realm.无: 0,
            Realm.练气: 100,
            Realm.筑基: 300,
            Realm.金丹: 800,
            Realm.元婴: 2000,
            Realm.化神: 5000,
            Realm.炼虚: 12000,
            Realm.合体: 30000,
            Realm.大乘: 80000,
            Realm.渡劫: 200000,
        }
    
    def get_player_status(self, player: Player) -> str:
        """获取玩家状态信息"""
        lines = [
            f"=== {player.name} 的修仙信息 ===",
            f"境界: {player.realm.name}",
            f"修为: {player.exp}",
            f"生命值: {player.hp}/{player.max_hp}",
            f"法力值: {player.mp}/{player.max_mp}",
            f"当前位置: {player.current_area}",
        ]
        
        # 显示下一境界所需经验
        next_realm = self._get_next_realm(player.realm)
        if next_realm:
            required_exp = self.realm_exp_requirements[next_realm]
            remaining_exp = required_exp - player.exp
            if remaining_exp > 0:
                lines.append(f"距离 {next_realm.name} 还需: {remaining_exp} 修为")
            else:
                lines.append(f"可以突破到 {next_realm.name}！")
        
        return "\n".join(lines)
    
    def get_inventory_info(self, player: Player) -> str:
        """获取背包信息"""
        if not player.inventory:
            return f"{player.name} 的背包是空的"
        
        lines = [f"=== {player.name} 的背包 ==="]
        
        # 按物品类型分组显示
        items_by_type = {}
        for item_name, count in player.inventory.items():
            item = self.game_core.items.get(item_name)
            if item:
                item_type = item.item_type.value
            else:
                item_type = "未知"
            
            if item_type not in items_by_type:
                items_by_type[item_type] = []
            items_by_type[item_type].append((item_name, count))
        
        for item_type, items in items_by_type.items():
            lines.append(f"\n【{item_type}】")
            for item_name, count in items:
                item = self.game_core.items.get(item_name)
                if item:
                    lines.append(f"  {item_name} x{count} - {item.description}")
                else:
                    lines.append(f"  {item_name} x{count}")
        
        return "\n".join(lines)
    
    def try_breakthrough(self, player: Player) -> Tuple[bool, str]:
        """尝试突破境界"""
        next_realm = self._get_next_realm(player.realm)
        if not next_realm:
            return False, "已达到最高境界"
        
        required_exp = self.realm_exp_requirements[next_realm]
        if player.exp < required_exp:
            remaining_exp = required_exp - player.exp
            return False, f"修为不足，还需要 {remaining_exp} 点修为才能突破到 {next_realm.name}"
        
        # 突破成功率计算（基础80%，可以根据物品等因素调整）
        success_rate = 0.8
        
        # 检查是否有辅助突破的物品
        breakthrough_items = self._get_breakthrough_items(player)
        for item_name, bonus in breakthrough_items.items():
            success_rate += bonus
            success_rate = min(success_rate, 0.95)  # 最高95%成功率
        
        # 进行突破判定
        if random.random() < success_rate:
            # 突破成功
            old_realm = player.realm
            player.realm = next_realm
            
            # 提升属性
            hp_increase = random.randint(20, 50)
            mp_increase = random.randint(20, 50)
            player.max_hp += hp_increase
            player.max_mp += mp_increase
            player.hp = player.max_hp  # 突破后满血满蓝
            player.mp = player.max_mp
            
            # 消耗突破物品
            for item_name in breakthrough_items.keys():
                if player.has_item(item_name):
                    player.remove_item(item_name, 1)
            
            return True, (f"恭喜！成功从 {old_realm.name} 突破到 {next_realm.name}！\n"
                         f"生命值上限增加 {hp_increase}，法力值上限增加 {mp_increase}")
        else:
            # 突破失败
            exp_loss = random.randint(10, 30)
            player.exp = max(0, player.exp - exp_loss)
            
            # 消耗突破物品
            for item_name in breakthrough_items.keys():
                if player.has_item(item_name):
                    player.remove_item(item_name, 1)
            
            return False, f"突破失败！损失了 {exp_loss} 点修为"
    
    def _get_next_realm(self, current_realm: Realm) -> Optional[Realm]:
        """获取下一个境界"""
        realm_list = list(Realm)
        try:
            current_index = realm_list.index(current_realm)
            if current_index < len(realm_list) - 1:
                return realm_list[current_index + 1]
        except ValueError:
            pass
        return None
    
    def _get_breakthrough_items(self, player: Player) -> Dict[str, float]:
        """获取玩家拥有的突破辅助物品"""
        breakthrough_items = {
            "筑基丹": 0.15,
            "金丹": 0.20,
            "破障丹": 0.10,
            "完整妖丹": 0.05,
        }
        
        available_items = {}
        for item_name, bonus in breakthrough_items.items():
            if player.has_item(item_name):
                available_items[item_name] = bonus
        
        return available_items
    
    def use_item(self, player: Player, item_name: str) -> Tuple[bool, str]:
        """使用物品"""
        if not player.has_item(item_name):
            return False, f"你没有 {item_name}"
        
        item = self.game_core.items.get(item_name)
        if not item:
            return False, f"未知物品: {item_name}"
        
        # 根据物品类型执行不同效果
        if item.item_type == ItemType.丹药:
            return self._use_pill(player, item_name, item)
        elif item.item_type == ItemType.功法:
            return self._use_skill_book(player, item_name, item)
        elif item.item_type == ItemType.灵石:
            return self._use_spirit_stone(player, item_name, item)
        elif item.item_type == ItemType.法宝:
            return self._use_treasure(player, item_name, item)
        elif item.item_type == ItemType.材料:
            return self._use_material(player, item_name, item)
        elif item.item_type == ItemType.其他:
            return self._use_other(player, item_name, item)
        else:
            return False, f"{item_name} 无法直接使用"
    
    def _use_pill(self, player: Player, item_name: str, item: Item) -> Tuple[bool, str]:
        """使用丹药"""
        player.remove_item(item_name, 1)
        
        if "妖丹" in item_name:
            exp_gain = random.randint(20, 50)
            player.exp += exp_gain
            return True, f"服用了 {item_name}，获得 {exp_gain} 点修为"
        elif "回血丹" in item_name:
            heal_amount = random.randint(30, 60)
            old_hp = player.hp
            player.hp = min(player.max_hp, player.hp + heal_amount)
            actual_heal = player.hp - old_hp
            return True, f"服用了 {item_name}，恢复 {actual_heal} 点生命值"
        elif "回蓝丹" in item_name:
            mp_amount = random.randint(30, 60)
            old_mp = player.mp
            player.mp = min(player.max_mp, player.mp + mp_amount)
            actual_mp = player.mp - old_mp
            return True, f"服用了 {item_name}，恢复 {actual_mp} 点法力值"
        else:
            exp_gain = random.randint(10, 30)
            player.exp += exp_gain
            return True, f"服用了 {item_name}，获得 {exp_gain} 点修为"
    
    def _use_skill_book(self, player: Player, item_name: str, item: Item) -> Tuple[bool, str]:
        """使用功法秘籍"""
        player.remove_item(item_name, 1)
        
        exp_gain = random.randint(50, 100)
        player.exp += exp_gain
        
        # 有概率学会新技能（这里简化处理）
        if random.random() < 0.3:
            skill_name = item_name.replace("残页", "").replace("手册", "")
            return True, f"研读了 {item_name}，获得 {exp_gain} 点修为，并领悟了 {skill_name}！"
        else:
            return True, f"研读了 {item_name}，获得 {exp_gain} 点修为"
    
    def _use_spirit_stone(self, player: Player, item_name: str, item: Item) -> Tuple[bool, str]:
        """使用灵石"""
        player.remove_item(item_name, 1)
        
        if "低阶" in item_name:
            exp_gain = random.randint(5, 15)
        elif "中阶" in item_name:
            exp_gain = random.randint(15, 35)
        elif "高阶" in item_name:
            exp_gain = random.randint(35, 70)
        else:
            exp_gain = random.randint(10, 25)
        
        player.exp += exp_gain
        
        # 有概率同时恢复法力值
        if random.random() < 0.5:
            mp_gain = exp_gain // 2
            old_mp = player.mp
            player.mp = min(player.max_mp, player.mp + mp_gain)
            actual_mp = player.mp - old_mp
            return True, f"吸收了 {item_name} 的灵气，获得 {exp_gain} 点修为和 {actual_mp} 点法力值"
        else:
            return True, f"吸收了 {item_name} 的灵气，获得 {exp_gain} 点修为"
    
    def rest(self, player: Player) -> str:
        """休息恢复"""
        hp_recover = random.randint(10, 30)
        mp_recover = random.randint(10, 30)
        
        old_hp = player.hp
        old_mp = player.mp
        
        player.hp = min(player.max_hp, player.hp + hp_recover)
        player.mp = min(player.max_mp, player.mp + mp_recover)
        
        actual_hp = player.hp - old_hp
        actual_mp = player.mp - old_mp
        
        return f"休息了一会儿，恢复 {actual_hp} 点生命值和 {actual_mp} 点法力值"
    
    def get_realm_info(self, realm: Realm = None) -> str:
        """获取境界信息"""
        if realm is None:
            lines = ["=== 修仙境界一览 ==="]
            for r in Realm:
                if r == Realm.无:
                    continue
                required_exp = self.realm_exp_requirements[r]
                lines.append(f"{r.name}: 需要 {required_exp} 修为")
            return "\n".join(lines)
        else:
            required_exp = self.realm_exp_requirements.get(realm, 0)
            return f"{realm.name} 境界需要 {required_exp} 修为"